package com.myscreen.ui;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.net.Socket;

public class ClientScreenPanel extends JPanel {
    private BufferedImage image;

    public void updateImage(Socket socket) throws Exception {
        DataInputStream in = new DataInputStream(socket.getInputStream());
        int imageLength = in.readInt();
        if (imageLength <= 0) {
            System.err.println("read bytes length is 0");
            return;
        }
        byte[] imageBytes = new byte[imageLength];
        in.readFully(imageBytes);
        image = ImageIO.read(new ByteArrayInputStream(imageBytes));

        repaint(); // 触发重绘

    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }
    }
}